package com.coocaa.ops.admin.v1.panel.service.impl;

import com.coocaa.ops.admin.base.event.AlterTransactionalEvent;
import com.coocaa.ops.admin.base.language.CommonLanguageProperties;
import com.coocaa.ops.admin.base.validator.InputParamsValidator;
import com.coocaa.ops.admin.v1.audit.AuditUtil;
import com.coocaa.ops.admin.v1.panel.async.AiPosterMergeServiceImpl;
import com.coocaa.ops.admin.v1.panel.convert.PanelCommonSaveConverter;
import com.coocaa.ops.admin.v1.panel.provider.IPanelInfoUpdateProvider;
import com.coocaa.ops.admin.v1.panel.service.IPanelInfoUpdateService;
import com.coocaa.ops.admin.v1.timedtask.TimedTaskUtil;
import com.coocaa.ops.admin.v1.timedtask.model.TimedInfoModel;
import com.coocaa.ops.common.core.base.enums.ResourceTypeEnum;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.base.util.ResourceStatusValidator;
import com.coocaa.ops.common.core.biz.audit.entity.AuditTaskInfoEntity;
import com.coocaa.ops.common.core.biz.auth.entity.SysUserEntity;
import com.coocaa.ops.common.core.biz.panel.entity.PanelInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author bjh
 * @description 板块信息原始表-更新service接口实现
 * @date 2020-06-15 14:40:18
 */
@Service
public class PanelInfoUpdateServiceImpl implements IPanelInfoUpdateService {
    @Autowired
    private IPanelInfoUpdateProvider thisUpdateProvider;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private AiPosterMergeServiceImpl aiPosterMergeService;
    private static CommonLanguageProperties commonLanguageProperties;

    /**
     * 保存
     *
     * @param inputEntity
     * @param user
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(PanelInfoEntity inputEntity, SysUserEntity user) {
        PanelCommonSaveConverter.handleSetDefaultValue(inputEntity);
        PanelInfoEntity entity = thisUpdateProvider.save(inputEntity, user.getId());
        //保存后的处理
        this.handleAfterSave(entity, user);

    }

    /**
     * 批量删除
     *
     * @param ids
     * @param user
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map deleteBatch(Integer[] ids, SysUserEntity user) {
        String result = thisUpdateProvider.deleteBatch(ids, user.getId());
        if (R.SUCCESS.equals(result)) {
            return R.ok().msg(commonLanguageProperties.getDeleteSuccess());
        } else {
            return R.fail(result);
        }
    }

    @Autowired
    public void setCommonLanguageProperties(CommonLanguageProperties commonLanguageProperties) {
        PanelInfoUpdateServiceImpl.commonLanguageProperties = commonLanguageProperties;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteHistory(Integer id, Integer version, SysUserEntity user) {
        thisUpdateProvider.deleteHistory(id, version, user.getId());
        AuditUtil.logicDelByIdAndVersionAndType(id, version, ResourceTypeEnum.PANEL.getValue());
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    /**
     * 保存后的处理
     *
     * @param entity
     */
    private void handleAfterSave(PanelInfoEntity entity, SysUserEntity userInfo) {
        //提交审核
        if (ResourceStatusValidator.isToAuditing(entity.getStatus())) {
            AuditTaskInfoEntity taskInfoEntity = AuditUtil.openTask(entity.getPanelName(), entity.getId(), entity.getCurrentVersion(), ResourceTypeEnum.PANEL.getValue(), entity.getSource(), userInfo, 1);
            // 处理定时任务设置
            handleTimedTask(entity, userInfo.getId());
            //发送事务监听的事件，这里充分利用jdk8的lambda表达式的优势，将处理任务一并发送
            applicationEventPublisher.publishEvent(new AlterTransactionalEvent(() -> {
                //处理海报合成
                Integer version = InputParamsValidator.isDuplicateExist(entity.getDuplicateVersion()) ? entity.getDuplicateVersion() : entity.getCurrentVersion();
                aiPosterMergeService.handleAiPosterMerge(entity.getId(), version);
            }));
        }

    }

    /**
     * 处理定时任务
     *
     * @param entity
     * @param userId
     */
    private void handleTimedTask(PanelInfoEntity entity, Integer userId) {
        TimedInfoModel timedInfoModel = TimedInfoModel.getTimedInfoModel(entity.getId(), entity.getCurrentVersion(), entity.getIsTiming(), entity.getReleaseTime(), userId);
        TimedTaskUtil.handleTimedTask(timedInfoModel, ResourceTypeEnum.PANEL.toString());
    }


}
